package com.sychip.fhc.app.wsn.screen

//import com.sychip.fhc.lib.echarts.EChartsDotWebView
//import com.sychip.fhc.lib.echarts.EChartsLineWebView
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Usb
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.usb.UsbDeviceDto
import com.fhc.view.DropdownBox
import com.fhc.view.FhcAppVersion
import com.fhc.view.NameValueDto
import com.sychip.fhc.APP
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.lib.base.FhcTopAppBar
import com.sychip.fhc.lib.base.rememberKeyboardState
import timber.log.Timber


@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun WsnSettingScreen(snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, viewModel: WsnSettingViewModel = hiltViewModel()) {
    val density = LocalDensity.current
    var boxHeightDp = 0.dp

    var maxHeight by remember { mutableStateOf(0.dp.coerceAtLeast(200.dp)) }


    Scaffold(
        modifier = Modifier.fillMaxSize().onGloballyPositioned { coordinates ->
            with(density) {
                maxHeight = coordinates.size.height.toDp() -80.dp  //减去 titlebar  和底部 navigationbar 高度  48.dp
            }
        },
        topBar = {
            FhcTopAppBar(title=APP.TITLE)
        }
    ) { innerPadding ->
//        if (maxHeight > 0.dp) {  //不判断就必须var maxHeight by remember { mutableStateOf(0.dp.coerceAtLeast(100.dp)) }
            val isKeyboardOpen by rememberKeyboardState()
            val keyboardHeight = with(density) {
                WindowInsets.ime.getBottom(density).toDp()
            }
            Box(modifier = Modifier.windowInsetsPadding(WindowInsets.ime).padding(top = innerPadding.calculateTopPadding()).heightIn(max = if (isKeyboardOpen) maxHeight - keyboardHeight else maxHeight).fillMaxWidth().onGloballyPositioned { coordinates ->
                // 在这里处理布局变化，例如记录当前的高度和位置
                if (boxHeightDp == 0.dp) {
                    with(density) {
                        boxHeightDp = coordinates.size.height.toDp()
                    }
//                    maxHeight = boxHeightDp
                }
            }) {

                val uiState by viewModel.uiState.collectAsStateWithLifecycle()

                val settingFlow by viewModel.settingFlow.collectAsStateWithLifecycle()

                SettingContent(
                    modifier = Modifier.fillMaxSize(),
                    viewModel = viewModel,
                    loading = uiState.isLoading,
                    dto = settingFlow.dataList[0],
                    onSettingSave ={dto->
                        viewModel.updateSetting(dto)
                    }
                )

                uiState.userMessage?.let { userMessage ->
                    val snackbarText = stringResource(userMessage)
                    LaunchedEffect(snackbarHostState, viewModel, userMessage, snackbarText) {
                        snackbarHostState.showSnackbar(snackbarText)
                        viewModel.snackbarMessageShown()
                    }
                }
            }
        }
//    }
}

//
//@OptIn(ExperimentalMaterialApi::class)
//@Composable
//private fun  aaa(){
//
//    val keyboardController = LocalSoftwareKeyboardController.current
//    val focusManager = LocalFocusManager.current
//    val scrollState = rememberScrollState()
//
//    Column(
//        modifier = Modifier
//            .fillMaxWidth()
//            .verticalScroll(state = scrollState)
//    ) {
//        // 第一个输入框
//        var title by remember { mutableStateOf("") }
//        OutlinedTextField(
//            value = title,
//            onValueChange = { title = it },
//            modifier = Modifier
//                .fillMaxWidth()
//                .onFocusChanged {
////                            isFocused = it.isFocused
//                },
//            label = { Text("标题") },
//        )
//
//        // 第二个输入框
//        var description by remember { mutableStateOf("") }
//        OutlinedTextField(
//            value = description,
//            onValueChange = { description = it },
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(200.dp)
//                .onFocusChanged {
////                            isFocused = it.isFocused
//                },
//            label = { Text("描述") },
//            keyboardActions = KeyboardActions(
//                onDone = {
//                    keyboardController?.hide()
//                    focusManager.clearFocus()
//                }
//            )
//        )
//
//        // 第二个输入框
//        var description1 by remember { mutableStateOf("") }
//        OutlinedTextField(
//            value = description1,
//            onValueChange = { description1 = it },
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(200.dp)
//                .onFocusChanged {
////                            isFocused = it.isFocused
//                },
//            label = { Text("描述") },
//            keyboardActions = KeyboardActions(
//                onDone = {
//                    keyboardController?.hide()
//                    focusManager.clearFocus()
//                }
//            )
//        )
//
//
//        // 第二个输入框
//        var description2 by remember { mutableStateOf("") }
//        OutlinedTextField(
//            value = description2,
//            onValueChange = { description2 = it },
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(200.dp)
//                .onFocusChanged {
////                            isFocused = it.isFocused
//                },
//            label = { Text("描述") },
//            keyboardActions = KeyboardActions(
//                onDone = {
//                    keyboardController?.hide()
//                    focusManager.clearFocus()
//                }
//            )
//        )
//
//        // 第二个输入框
//        var description3 by remember { mutableStateOf("") }
//        OutlinedTextField(
//            value = description3,
//            onValueChange = { description3 = it },
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(200.dp)
//                .onFocusChanged {
////                            isFocused = it.isFocused
//                },
//            label = { Text("描述") },
//            keyboardActions = KeyboardActions(
//                onDone = {
//                    keyboardController?.hide()
//                    focusManager.clearFocus()
//                }
//            )
//        )
//        // 第二个输入框
//        var description4 by remember { mutableStateOf("") }
//        OutlinedTextField(
//            value = description4,
//            onValueChange = { description4 = it },
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(200.dp)
//                .onFocusChanged {
////                            isFocused = it.isFocused
//                },
//            label = { Text("描述") },
//            keyboardActions = KeyboardActions(
//                onDone = {
//                    keyboardController?.hide()
//                    focusManager.clearFocus()
//                }
//            )
//        )
//
//        // 提交按钮
//        Button(
//            onClick = {
//                keyboardController?.hide()
//                focusManager.clearFocus()
//            },
//            modifier = Modifier.padding(16.dp)
//        ) {
//            Text("保存设置")
//        }
//    }
//}

@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun SettingContent(
    modifier: Modifier = Modifier,
    viewModel: WsnSettingViewModel = hiltViewModel(),
    loading: Boolean,
    dto:WsnSettingDto, // MutableState<WsnSettingDto> = remember {mutableStateOf(WsnSettingDto())}
    onSettingSave: (WsnSettingDto) -> Unit,
    keyboardController: SoftwareKeyboardController? = null,
) {
    val focusManager = LocalFocusManager.current
    if (loading) {
//是否在刷新
        var isRefreshing by remember{ mutableStateOf(true) }
        //下拉刷新的状态管理
        val pullRefreshState = rememberPullRefreshState(
            refreshing = isRefreshing,
            onRefresh = { isRefreshing = true }
        )
        //刷新时的业务处理
        if (isRefreshing) {
//            onRefreshing()
            isRefreshing = false    //刷新业务执行完毕后修改状态
        }
        Box(modifier = modifier
            .fillMaxSize()
            .pullRefresh(state = pullRefreshState)
        ) {
//            content()
            PullRefreshIndicator(
                refreshing = isRefreshing,
                state = pullRefreshState,
                modifier = Modifier.align(Alignment.TopCenter)
            )
        }
    } else {


        val usbFlow by viewModel.usbFlow.collectAsStateWithLifecycle()
        var setting by remember {mutableStateOf(dto)}
        Column(
            modifier
                .fillMaxSize().verticalScroll(rememberScrollState()).imePadding().onGloballyPositioned { coordinates ->
                    // 在这里处理布局变化，例如记录当前的高度和位置
                }
        ) {


            // 设备概览卡片
            DeviceOverviewCard(usbFlow.usb)

//            EChartsLineWebView()
//            EChartsDotWebView()
            AppTypeDropdownMenu()

            DropdownBox( selectedItem = dto.selectedItem,items = List(30) { index ->
                NameValueDto("选项${index + 1}", "value${index + 1}")
            },onValueChange = {
                setting = setting.copy(selectedItem = it)
            })

            val textFieldColors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = Color.Transparent,
                unfocusedBorderColor = Color.Transparent,
                cursorColor = colorScheme.secondary
            )



            OutlinedTextField(
                value = setting.title,
                modifier = Modifier.fillMaxWidth(),
                onValueChange = {
                    setting = setting.copy(title = it)
                },
                placeholder = {
                    Text(
                        text = stringResource(id = R.string.title_hint),
                        style = MaterialTheme.typography.titleLarge
                    )
                },
                textStyle = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
                maxLines = 1,
                colors = textFieldColors
            )

            OutlinedTextField(
                value = setting.description,
                onValueChange =  {it->
                    setting = setting.copy(description = it)
                },
                placeholder = {
                    Text(stringResource(id = R.string.description_hint))
                },
                modifier = Modifier
                    .height(350.dp)
                    .fillMaxWidth(),
                colors = textFieldColors
            )


            // 提交按钮
            Button(
                onClick = {
                    keyboardController?.hide()
                    focusManager.clearFocus()
//                    viewModel.saveSettings(title, description)
                    onSettingSave(setting)
                },
                modifier = Modifier.padding(16.dp)
            ) {
                Text("保存设置")
            }
            FhcAppVersion(R.string.wsn_copyright)
        }
    }
}


@Composable
private fun AppTypeDropdownMenu(
) {
    var expanded by remember { mutableStateOf(false) }

    var isItem1Selected by remember { mutableStateOf(false) }
    var isItem2Selected by remember { mutableStateOf(false) }


    val content: @Composable ColumnScope.(() -> Unit) -> Unit = { closeMenu ->
        DropdownMenuItem(
            modifier = Modifier.wrapContentSize(),
            onClick = {
                isItem1Selected = !isItem1Selected

                closeMenu()
            },
            text = { Text(text = "Setting") },
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Settings,
                    contentDescription = null,
                    tint = Color.Blue
                )
            },
            trailingIcon = {
                if (isItem1Selected) {
                    Icon(
                        modifier = Modifier.size(20.dp),
                        imageVector = Icons.Default.Check,
                        contentDescription = null,
                        tint = Color.Blue
                    )
                } else {
                    Box(
                        modifier = Modifier.size(20.dp).background(Color.Red)
                    )
                }
            },
            contentPadding = MenuDefaults.DropdownMenuItemContentPadding,
        )

        DropdownMenuItem(
            modifier = Modifier.wrapContentSize(),
            onClick = {
                isItem2Selected = !isItem2Selected

                closeMenu()
            },
            text = { Text(text = stringResource(id = R.string.refresh)) },
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Refresh,
                    contentDescription = null,
                    tint = Color.Blue
                )
            },
            trailingIcon = {
                if (isItem2Selected) {
                    Icon(
                        modifier = Modifier.size(20.dp),
                        imageVector = Icons.Default.Check,
                        contentDescription = null,
                        tint = Color.Blue
                    )
                } else {
                    null
                }
            },
        )
    }


    Box{
        IconButton(onClick = { expanded = !expanded }, colors= IconButtonDefaults.iconButtonColors( containerColor= Color.Gray,
            contentColor = Color.Blue,)) {
            Icon(Icons.Filled.MoreVert, stringResource(id = R.string.menu_more), tint=Color.Red)
        }
        DropdownMenu(
            expanded = expanded,
            offset= DpOffset((30).dp, 0.dp),
            onDismissRequest = { expanded = false },
            properties = PopupProperties(dismissOnClickOutside = true),
            modifier = Modifier.wrapContentSize(Alignment.TopEnd)

        ) {
            content { expanded = !expanded }
        }
    }
}


@Composable
private fun DeviceOverviewCard(device: UsbDeviceDto?) {
    Card( modifier = Modifier.fillMaxWidth().padding(top = 16.dp, start =16.dp, end =16.dp, bottom =6.dp, ),
        colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))) {
        Row(
            modifier = Modifier,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.Usb,
                contentDescription = null,
                tint = colorScheme.primary,
                modifier = Modifier.size(48.dp)
            )
            Spacer(modifier = Modifier.width(16.dp))
            Column {
                Text(
                    text = device?.deviceName ?: "--",
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold,
                    color = colorScheme.onPrimaryContainer
                )
                Text(
                    text = device?.productName ?: "--",
                    style = MaterialTheme.typography.titleMedium,
                    color = colorScheme.onPrimaryContainer
                )
            }
        }
    }

    var items: List<Pair<String, String>>
    if(device == null){
         items = listOf(
            "Vendor ID" to "--",
            "Product ID" to "--",
            "Device Protocol" to "--",
            "Manufacturer Name" to "--",
            "Serial Number" to "--",
            "Configuration Count" to "--",
        )
    }else {
         items = listOf(
            "Vendor ID" to "0x${device.vendorId.toString(16).uppercase()}",
            "Product ID" to "0x${device.productId.toString(16).uppercase()}",
            "Device Protocol" to device.deviceProtocol.toString(),
            "Manufacturer Name" to (device.manufacturerName ?: "Unknown"),
            "Serial Number" to (device.serialNumber ?: "Unknown"),
            "Configuration Count" to device.configurationCount.toString()
        )
    }

    Card(
        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
        colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))) {
        Column(modifier = Modifier.padding(16.dp)) {
//            Text(
//                text = "技术规格",
//                style = MaterialTheme.typography.titleLarge,
//                modifier = Modifier.padding(bottom = 8.dp),
//                color = colorScheme.onPrimaryContainer
//            )
            items.forEach { (label, value) ->
                DetailRow(label, value)
                HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp), thickness = DividerDefaults.Thickness, color = DividerDefaults.color)
            }
        }
    }
}

@Composable
private fun DetailRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = colorScheme.onPrimaryContainer
        )
        Text(
            text = value,
            style = MaterialTheme.typography.bodyLarge,
            fontWeight = FontWeight.Medium,
            color = colorScheme.onPrimaryContainer
        )
    }
}
